<template>
    <div class="page-wrap">
        <!-- <div style="color: rgb(27, 76, 184);margin-bottom: 15px">
            <div class="addressIcon"></div>
            <span>当前位置：</span>
            <span style="cursor: pointer" @click="returnImage">镜像管理</span>
            <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
            <span style="color: #333">{{titleText}}</span>
        </div> -->
        <div class="page-content" :style="{height:contentHei}">
            <div class="img-header">
                <div style="font-weight: 700;font-size: 18px">{{titleText}}</div>
            </div>
            <Divider />
            <div class="content-wrap">
                <!-- <Form ref="creatImageFormValidate" :model="creatImageFormValidate" :rules="creatImageRuleValidate" :label-width="120" style="width: 500px">
                    <FormItem label="名称" prop="imageName">
                        <Input v-model.trim="creatImageFormValidate.imageName" placeholder="名称"></Input>
                    </FormItem>
                    <FormItem label="硬盘最小值" prop="mindisk">
                        <InputNumber :max="1024"  :step="1" v-model="creatImageFormValidate.mindisk" style="width: 130px"></InputNumber>
                    </FormItem>
                    <FormItem label="内存最小值" prop="minram">
                        <InputNumber :max="65536" :step="1" v-model="creatImageFormValidate.minram" style="width: 130px"></InputNumber>
                    </FormItem>
                    <FormItem label="Profile" prop="profileId">
                        <Select filterable v-model="creatImageFormValidate.profileId" placeholder="Select profile">
                            <Option :value="value.id" v-for="(value,index) in profileList" :key="index" v-if="value.status == 1">{{value.osname}}</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="系统类型" prop="systype">
                        <Select filterable v-model="creatImageFormValidate.systype" placeholder="选择系统类型">
                            <Option value="linux">Linux</Option>
                            <Option value="windows2003">Windows2003</Option>
                            <Option value="unix">Unix</Option>
                            <Option value="windows7">Windows7</Option>
                            <Option value="windowsXP">WindowsXP</Option>
                            <Option value="windows">Windows</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="虚拟机类型" prop="vtype">
                        <RadioGroup v-model="creatImageFormValidate.vtype">
                            <Radio label="kvm">kvm</Radio>
                            <Radio label="docker">docker</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="可见范围" prop="localvisibility">
                        <RadioGroup v-model="creatImageFormValidate.localvisibility">
                            <Radio label="share">单位</Radio>
                            <Radio label="private">个人</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="设备类型" prop="devicetype">
                        <Select filterable v-model="creatImageFormValidate.devicetype" placeholder="选择设备类型">
                            <Option value="VM">VM</Option>
                            <Option value="firewall">firewall</Option>
                            <Option value="IDS">IDS</Option>
                            <Option value="WAF">WAF</Option>
                            <Option value="Drout">Drout</Option>
                            <Option value="DES">DES:离散事件仿真节点</Option>
                            <Option value="base">BASE</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="HasQga" prop="hasQga">
                        <i-switch v-model="creatImageFormValidate.hasQga" size="large">
                            <span slot="open">true</span>
                            <span slot="close">false</span>
                        </i-switch>
                    </FormItem>
                    <FormItem label="HasVirtioDriver" prop="HasVirtioDriver">
                        <i-switch v-model="creatImageFormValidate.HasVirtioDriver" size="large">
                            <span slot="open">true</span>
                            <span slot="close">false</span>
                        </i-switch>
                    </FormItem>
                    <FormItem label="HasHtPlug" prop="hasHtPlug">
                        <i-switch v-model="creatImageFormValidate.hasHtPlug" size="large">
                            <span slot="open">true</span>
                            <span slot="close">false</span>
                        </i-switch>
                    </FormItem>
                    <FormItem label="HasCloudInit" prop="hasCloudInit">
                        <i-switch v-model="creatImageFormValidate.hasCloudInit" size="large">
                            <span slot="open">true</span>
                            <span slot="close">false</span>
                        </i-switch>
                    </FormItem>
                    <FormItem v-show="showUploadFile" label="上传文件" prop="file">
                        <Upload
                                v-model="creatImageFormValidate.file"
                                :action="updateUrl"
                                :before-upload="handleUpload">
                            <Button icon="ios-cloud-upload-outline" :disabled="setDisabled">选择文件</Button>
                        </Upload>
                        <div v-if="creatImageFormValidate.file !== null">
                            <p>文件名: {{ creatImageFormValidate.file.name }}</p>
                            <p>size:<span v-text="fileSize"></span></p>
                            <Progress :percent="progress"></Progress>
                            <p>speed:<span v-text="speed"></span></p>
                        </div>
                    </FormItem>
                    <FormItem label="描述" prop="description">
                        <Input v-model.trim="creatImageFormValidate.description" type="textarea"
                               :autosize="{minRows: 2,maxRows: 5}" placeholder="描述" :maxlength="200"></Input>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="submitBtn('creatImageFormValidate')" :loading="addImageBtnLoading" :disabled="setDisabled">确定</Button>
                        <Button @click="creatImageHandleReset('creatImageFormValidate')" style="margin-left: 8px">重置</Button>
                    </FormItem>
                </Form> -->
            </div>
        </div>
    </div>
</template>
<script>
    import {getProfile,modifyImg,getDetailByID} from '@/api/image.js'
    export default {
        components:{},
        data () {
            const validateUpload = (rule, value, callback) => {
                if (this.creatImageRuleValidate.file === null) {
                    callback(new Error('Please select the file to upload'))
                } else {
                    callback()
                }
            }
            const validateMinram = (rule,value,callback) => {
                let val = parseInt(value)
                if(val >= 128 && val <= 65536){
                    callback()
                }else {
                    callback(new Error('Ram range in size from 128 MB to 65536 MB'))
                }
            }
            const validateMindisk = (rule,value,callback) => {
                let val = parseInt(value)
                if(val >= 1 && val <= 1024){
                    callback()
                }else {
                    callback(new Error('Disk range in size from 1 GB to 1024 GB'))
                }
            }
            return {
                fullHeight: document.documentElement.clientHeight,
                fullWidth: document.documentElement.clientWidth,
                contentHei:'auto',
                // 先判断状态
                isCreate:true,
                receiveData:{},
                showUploadFile:true,
                imageID:'',
                // 页面标题
                titleText:'',
                // 表单
                updateUrl:`/api/virtual/image/createimagev3`,
                // updateUrl:`http://172.18.100.1/virtual/image/createimagev3`,
                addImageBtnLoading:false,
                creatImageFormValidate:{
                    imageName:'',
                    mindisk:0,
                    minram:0,
                    profileId:'',
                    systype:'',
                    vtype:'kvm',
                    localvisibility:'share',
                    devicetype:'VM',
                    hasQga:false,
                    HasVirtioDriver:false,
                    hasHtPlug:false,
                    hasCloudInit:false,
                    description:'',
                    file:null,
                },
                creatImageRuleValidate:{
                    imageName: [
                        { required: true, message: '名称不能为空', trigger: 'change' },
                        { max: 64, message: '名称不能超过64个字母', trigger: 'change' },
                    ],
                    vtype: [
                        { required: true, message: '名称不能超过64个字母 ', trigger: 'change' }
                    ],
                    localvisibility: [
                        { required: true, message: '可见范围不能为空 ', trigger: 'change' }
                    ],
                    systype:[
                        { required: true, message: 'The systype cannot be empty', trigger: 'change' }
                    ],
                    file: [
                        { required: true, validator: validateUpload, trigger: 'change' }
                    ],
                    minram:[
                        { required: true, validator: validateMinram, trigger: 'change' },
                    ],
                    mindisk:[
                        { required: true, validator: validateMindisk, trigger: 'change' },
                    ],
                    description:[
                        { max: 200, message: 'The desc cannot exceed 200 letters', trigger: 'change' },
                    ],
                },
                speed:0,
                loaded:0,
                fileSize:0,
                progress:0,
                setDisabled:false,
                //profile
                profileList:[],
            }
        },
        computed:{

        },
        created(){
            this.getProfileData()
        },
        mounted(){
            // 是创建还是修改
            if(this.$route.query.action === 'create'){
                this.isCreate = true
                this.showUploadFile = true
                this.titleText = '创建镜像'
            }else if(this.$route.query.action === 'modify'){
                this.isCreate = false
                this.showUploadFile = false   // 修改镜像不用再上传文件
                this.titleText = '修改镜像'
                this.imageID = this.$route.query.id
                this.getImageInfo()
            }
            this.addBreadItem({ name: this.titleText });
            this.setStyle()
            window.onresize = () => {
                this.setStyle()
            }
        },
        methods:{
            // 设置高度
            setStyle(){
                window.fullHeight = document.documentElement.clientHeight;
                window.fullWidth = document.documentElement.clientWidth;
                this.fullHeight = window.fullHeight;
                this.fullWidth = window.fullWidth;
                this.contentHei =   this.fullHeight - 80 - 60 - 21 +'px'  // 80是头部高度  60是上下padding
            },
            // 返回镜像管理
            returnImage(){
                this.$router.push({
                    name: 'image',
                    query:{
                        page:this.$route.query.page,
                    }
                })
            },
            // 获取镜像数据 回显
            getImageInfo(){
                getDetailByID(this.imageID)
                    .then(res=>{
                        if(res.data.code === 1){
                            let imageDate = res.data.attribute.imageDate
                            this.creatImageFormValidate.imageName = imageDate.imagename;
                            this.creatImageFormValidate.mindisk = imageDate.mindisk;
                            this.creatImageFormValidate.minram = imageDate.minram;
                            this.creatImageFormValidate.profileId = imageDate.profileId;
                            this.creatImageFormValidate.systype = imageDate.systype;
                            this.creatImageFormValidate.vtype = imageDate.vtype;
                            this.creatImageFormValidate.localvisibility = imageDate.localvisibility;
                            this.creatImageFormValidate.devicetype = imageDate.devicetype;
                            this.creatImageFormValidate.hasQga = imageDate.hasqga;
                            this.creatImageFormValidate.HasVirtioDriver = imageDate.HasVirtioDriver;
                            this.creatImageFormValidate.hasHtPlug = imageDate.hashtplug?imageDate.hashtplug:false;
                            this.creatImageFormValidate.hasCloudInit = imageDate.hascloudinit;
                            this.creatImageFormValidate.description = imageDate.description;
                        }
                    })
                    .catch(err=>{
                        console.log(err)
                    })
            },
            //  profile
            getProfileData(){
                getProfile()
                    .then(res=>{
                        if(res.data.code == 1){
                            this.profileList = res.data.attribute.list;
                        }else {
                            this.$Message.error('获取镜像列表失败！')
                        }
                    })
                    .catch(err=>{
                        console.log(err)
                        this.$Message.error('服务连接失败！')
                    })

            },
            // 提交镜像
            submitBtn(name){
                if(this.isCreate){
                    this.creatImageHandleSubmit(name)
                }else {
                    this.modifyImage(name)
                }
            },
            creatImageHandleSubmit(name){
                let _this = this
                let param = {
                    imagename: _this.creatImageFormValidate.imageName,
                    mindisk: _this.creatImageFormValidate.mindisk + '',
                    minram: _this.creatImageFormValidate.minram + '',
                    localvisibility:_this.creatImageFormValidate.localvisibility,
                    vtype: _this.creatImageFormValidate.vtype,
                    devicetype: _this.creatImageFormValidate.devicetype,
                    systype: _this.creatImageFormValidate.systype,
                    hasqga: _this.creatImageFormValidate.hasQga + '',
                    hascloudinit: _this.creatImageFormValidate.hasCloudInit + '',
                    HasVirtioDriver: _this.creatImageFormValidate.HasVirtioDriver + '',
                    hashtplug: _this.creatImageFormValidate.hasHtPlug + '',
                    description: _this.creatImageFormValidate.description,
                    profileId: _this.creatImageFormValidate.profileId,
                    file:_this.creatImageFormValidate.file
                }
                for (let key in param) {
                    if (!param[key]) {
                        param[key] = null
                    }
                }
                let params = _this.$Qs.stringify(param, { skipNulls: true })
                this.$refs[name].validate((valid) =>{
                    if(valid){
                        let formData = new window.FormData()
                        formData.append('file',_this.creatImageFormValidate.file);
                        _this.addImageBtnLoading = true
                        _this.setDisabled = true
                        _this.axios({
                            method:'post',
                            url:`${_this.updateUrl}?${params}`,
                            data:formData,
                            headers:{
                                'Content-type':'multipart/form-data',
                            },
                            timeout:0,
                            onUploadProgress: progressEvent => {
                                var complete = Math.floor(progressEvent.loaded / progressEvent.total * 100)
                                _this.progress = complete
                                function getspeed () {
                                    var aaspeed = Number(progressEvent.loaded - _this.loaded)
                                    _this.loaded = progressEvent.loaded
                                    if (aaspeed > 1024 * 1024) {
                                        _this.speed = (Math.round(aaspeed * 100 / (1024 * 1024)) / 100).toString() + 'MB/s'
                                    } else {
                                        _this.speed = (Math.round(aaspeed * 100 / 1024) / 100).toString() + 'KB/s'
                                    }
                                }
                                setInterval(getspeed(), 1000)
                            }
                        })
                            .then(res=>{
                                if(res.data.code == 1){
                                    _this.creatImageFormValidate.file = null
                                    if(_this.progress === 100){
                                        _this.$Message.success({
                                            content:'创建成功！',
                                            duration:3,
                                        })
                                        setTimeout(()=>{
                                            this.returnImage()
                                        },3000)
                                    }
                                }else {
                                    _this.$Message.error('提交失败！')
                                    _this.setDisabled = false
                                }
                                _this.addImageBtnLoading = false
                            })
                            .catch(err=>{
                                console.log(err)
                                _this.$Message.error('服务器连接失败！')
                                _this.addImageBtnLoading = false
                                _this.setDisabled = false
                            })
                    }else {
                        _this.$Message.error('请完善信息！');
                    }
                })
            },
            creatImageHandleReset(name){
                this.$refs[name].resetFields();
            },
            handleUpload(file){
                // 新加上传过程
                if (file) {
                    if (file.size > 1024 * 1024) {
                        this.fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'
                    } else {
                        this.fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'
                    }
                }
                this.creatImageFormValidate.file = file;
                return false;
            },
            // 修改镜像
            modifyImage(name){
                let _this = this
                this.$refs[name].validate((valid) =>{
                    if(valid){
                        let formData = {
                            imagename: _this.creatImageFormValidate.imageName,
                            systype: _this.creatImageFormValidate.systype,
                            description: _this.creatImageFormValidate.description,
                            localvisibility:_this.creatImageFormValidate.localvisibility,
                            vtype: _this.creatImageFormValidate.vtype,
                            mindisk: _this.creatImageFormValidate.mindisk+ '',
                            minram: _this.creatImageFormValidate.minram + '',
                            hasqga: _this.creatImageFormValidate.hasQga + '',
                            HasVirtioDriver: _this.creatImageFormValidate.HasVirtioDriver + '',
                            hashtplug: _this.creatImageFormValidate.hasHtPlug + '',
                            hascloudinit: _this.creatImageFormValidate.hasCloudInit + '',
                            devicetype: _this.creatImageFormValidate.devicetype,
                            profile_id: _this.creatImageFormValidate.profileId,
                        };
                        let params = {
                            id:this.imageID,
                            data:formData
                        }
                        _this.addImageBtnLoading = true
                        _this.setDisabled = true
                        modifyImg(params)
                            .then(res=>{
                                if(res.data.code == 1){
                                    _this.$Message.success({
                                        content:'修改成功！',
                                        duration:3,
                                    })
                                    setTimeout(()=>{
                                        this.returnImage()
                                    },3000)
                                }else {
                                    _this.$Message.error({
                                        content:'镜像修改失败',
                                        duration:3
                                    })
                                    _this.setDisabled = false
                                }
                                _this.addImageBtnLoading = false
                            })
                            .catch(err=>{
                                _this.addImageBtnLoading = false
                                _this.setDisabled = false
                                console.log(err)
                            })
                    }else {
                        this.$Message.error({
                            content:'请完善信息！',
                            duration:3,
                        });
                    }
                })
            },
        },
        beforeDestroy(){
            this.setDisabled=false
        },
        beforeRouteLeave (to, from, next) {
            if(to.path === '/image'){
                to.query.page = this.$route.query.page
                next()
            }else {
                next()
            }
        },
    }
</script>
<style scoped>
    .page-wrap{
        padding: 15px 30px 30px 30px;
    }
    .page-content{
        background-color: #fff;
        border-radius: 10px;
    }
    .img-header{
        display: flex;
        justify-content: space-between;
        padding: 20px 20px 0 20px;
    }
    .addressIcon{
        display: inline-block;
        height: 14px;
        width: 12px;
        background: url("../../assets/globalIcon/addressIcon.png") no-repeat center;
        background-size: 100% 100%;
        margin-bottom: -1px;
    }
    .content-wrap{
        overflow-x: hidden;
        overflow-y: auto;
        padding: 0 20px;
        height: calc(100% - 96px);
    }
</style>
